% CS 233B
% Problem Set 1
% Problem 1

% load data
readYaleFaces;

% part d 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Your Code Here -- part a %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Subtract mean image
ma=mean(A,2);
A=A-ma*ones(1,size(A,2));

% SVD
[U,S,V]=svds(A,25);

% remember to report first 5 singular values 
fprintf('first 5 singular values:\n');
d=diag(S);
disp(d(1:5));

% part e -- determine accuracy and threshold
% create a variable norm_error = || y - y_{proj} ||_2 to be used to compare to
% threshold below to determine accuracy

for i = 1:20
    clear x
    testFileName = ['image' num2str(i)];
    x = eval(testFileName);
    x = double(reshape(x,size(x,1)*size(x,2),1));
    
    % Your Code Here -- part b %
    x=x-ma;
    e=x'-x'*U*U';
    norm_error(i)=e*e';
end




% Don't change this code, you can use it to report number of correct
% classifications
num_gnd_truth = 20;
gnd_truth = ones(num_gnd_truth,1);
gnd_truth(1) = 0;
gnd_truth(3) = 0;
gnd_truth(6) = 0;
gnd_truth(12) = 0;
gnd_truth(14) = 0;

thres = 10^8*[.009 .09 .9 9];
num_correct = 0;
best=0;
for i = 1:length(thres)
    for j = 1:length(gnd_truth)
        if ( norm_error(j) < thres(i) && gnd_truth(j) == 1)
            num_correct = num_correct + 1;
        elseif (norm_error(j) > thres(i) && gnd_truth(j) == 0)
            num_correct = num_correct + 1;
        end
    end
    if best<num_correct
        best=num_correct;
        besti=i;
    end
    num_correct
    num_correct = 0;
end
fprintf('best tao: %f\n',thres(besti));
fprintf('number of correct detections: %d\n',best);
